<template>
  <div>
    <van-nav-bar title="联系人列表" left-arrow @click-left="onClickLeft" />
    <van-address-edit
      :area-list="areaList"
      show-delete
      ref="area"
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
    />
  </div>
</template>

<script>
import { AddressEdit, NavBar, Toast, Area } from "vant";
import { areaList } from "@/assets/area/index.js";
import { addAddress, getAddressDetail,delAddress } from "@/network/index.js";
export default {
  name: "ContactEdit",
  data() {
    return {
      areaList,
      addressId:0,
    };
  },
  components: {
    [AddressEdit.name]: AddressEdit,
    [Toast.name]: Toast,
    [NavBar.name]: NavBar,
    [Area.name]: Area,
  },
  methods: {
    onClickLeft() { //回退
      this.$router.back();
    },
    async onSave(AddressInfo) { //点击保存按钮时
      const info = { //记录当前输入信息
        name: AddressInfo.name,
        tel: AddressInfo.tel,
        province: AddressInfo.province,
        city: AddressInfo.city,
        county: AddressInfo.county,
        addressDetail: AddressInfo.addressDetail,
        isDefault: AddressInfo.isDefault,
      };
      const {data} = await addAddress(info) //发送保存联系人地址请求
      // console.log(res);
      if(data.errno === 0) { //如果成功
        Toast("保存成功"); //提示保存成功
         await delAddress({id:this.addressId}) //删除当前地址
        this.$router.back() //返回上一页
      }
    },
    async onDelete() { //删除请求
      const {data} = await delAddress({id:this.addressId}) //发送删除请求根据data里面的地址id
      if(data.errno === 0) { 
        Toast.success('删除成功');
        this.$router.back()
      }
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [];
      } else {
        this.searchResult = [];
      }
    },
    async getAddressDetail(id) { //获取地址详情
      const {data: {data}} = await getAddressDetail({ id }); 
      this.addressId = data.id //保存当前地址的id
      //通过this.$refs拿到输入框绑定的数据并把请求下来的地址详情数据赋值上去
      this.$refs.area.data.name = data.name 
      this.$refs.area.data.addressDetail = data.addressDetail
      this.$refs.area.data.city = data.city
      this.$refs.area.data.county = data.county
      this.$refs.area.data.province = data.province
      this.$refs.area.data.tel = data.tel
      this.$refs.area.data.isDefault = data.isDefault
    },
   
  },
  created() {
    // console.log(AddressInfo);
  },
  mounted() {
    const id = this.$route.query.id; //组件实例挂载后查询是否有路由传过来的id
    if (id) { //如果有
      this.getAddressDetail(id); //就根据id来请求
    }
    
  },
};
</script>

<style lang="less" scoped>
</style>

